package com.xinchili.autoddl.autoClass.resolver;

import com.baomidou.mybatisplus.annotation.TableField;
import com.xinchili.autoddl.autoClass.strategy.ColumnCommentResolver;
import com.xinchili.autoddl.autoClass.strategy.ColumnNameResolver;
import com.xinchili.autoddl.autoClass.strategy.ColumnTypeResolver;
import com.xinchili.autoddl.autoClass.strategy.TableCommentResolver;
import com.xinchili.autoddl.autoClass.util.CommontUtil;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;

public abstract class AbstractDdlResolver implements
        ColumnNameResolver,
        ColumnTypeResolver,
        TableCommentResolver,
        ColumnCommentResolver {

    // 改为protected，子类可以直接访问
    protected final Map<Class<?>, String> sqlTypes = initDefaultSqlTypes();

    // 初始化默认类型映射
    private Map<Class<?>, String> initDefaultSqlTypes() {
        Map<Class<?>, String> types = new HashMap<>();
        types.put(String.class, "VARCHAR(255)");
        types.put(int.class, "INT");
        types.put(Integer.class, "INT");
        types.put(long.class, "BIGINT");
        types.put(Long.class, "BIGINT");
        types.put(boolean.class, "TINYINT(1)");
        types.put(Boolean.class, "TINYINT(1)");
        types.put(java.util.Date.class, "DATETIME");
        types.put(java.time.LocalDate.class, "DATE");
        types.put(java.time.LocalDateTime.class, "DATETIME");
        return types;
    }

    // 提供获取类型映射的方法
    public Map<Class<?>, String> getSqlTypes() {
        return sqlTypes;
    }

    // 提供添加类型映射的方法
    public void addSqlType(Class<?> javaType, String sqlType) {
        sqlTypes.put(javaType, sqlType);
    }

    // 默认的列名解析实现
    @Override
    public String resolveColumnName(Field field) {
        TableField anno = field.getAnnotation(TableField.class);
        if (anno != null && !anno.exist()) return null;
        if (anno != null && !anno.value().isEmpty()) return anno.value();
        return CommontUtil.camelToUnderline(field.getName());
    }

    // 默认的列类型解析实现
    @Override
    public String resolveColumnType(Field field) {
        Class<?> type = field.getType();
        return sqlTypes.getOrDefault(type, "TEXT");
    }

    // 默认的表注释解析实现
    @Override
    public String resolveTableComment(Class<?> clazz) {
        ApiModel anno = clazz.getAnnotation(ApiModel.class);
        return anno != null ? anno.value() : "";
    }

    // 默认的列注释解析实现
    @Override
    public String resolveColumnComment(Field field) {
        ApiModelProperty anno = field.getAnnotation(ApiModelProperty.class);
        return anno != null ? anno.value() : "";
    }


}